<!--系统管理-->
<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <el-input v-model="listQuery.title" placeholder="请输入系统标题" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @filter-change="handleFilterHandler"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="50" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="系统编码" prop="code" width="180">
          <template slot-scope="scope">
            <i v-if="scope.row.isDefault===1" class="el-icon-lock color-danger" />
            <copy-text :content="scope.row.code" position="left" />
          </template>
        </el-table-column>
        <el-table-column label="系统名称" min-width="240" prop="title" />
        <el-table-column :show-overflow-tooltip="true" label="系统描述" prop="description" min-width="260" />
        <el-table-column
          column-key="systemType"
          :filters="systemTypeOptions"
          :filter-multiple="false"
          label="系统类型"
          prop="systemType"
          width="100"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.systemType==0">内部</span>
            <span v-if="scope.row.systemType==1">外部</span>
            <span v-if="scope.row.systemType==2">三方</span>
            <span v-if="scope.row.systemType==90">自带</span>
          </template>
        </el-table-column>
        <el-table-column label="系统默认" prop="isDefault" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isDefault==0" class="color-danger">内部</span>
            <span v-if="scope.row.isDefault==1" class="color-success">默认</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="orders" sortable width="100" align="center" :show-overflow-tooltip="true" />

        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column prop="modifyBy" align="center" label="最后修改" width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">{{ scope.row.modifyBy | optionUserFormat }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>1" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="pageSystem" />
    </div>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow =!sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="systemRules"
          :model="systemRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="系统编码:" prop="code">
            <el-input v-model="systemRecord.code" :disabled="sideBox.status==='update'" placeholder="请输入" maxlength="15" show-word-limit />
          </el-form-item>
          <el-form-item label="系统标题:" prop="title">
            <el-input v-model="systemRecord.title" maxlength="15" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="系统路径:" prop="basePath">
            <el-input v-model="systemRecord.basePath" maxlength="100" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="内置系统:" prop="isDefault">
            <el-radio v-model="systemRecord.isDefault" :disabled="sideBox.status==='update'" :label="0">否</el-radio>
            <el-radio v-model="systemRecord.isDefault" :disabled="sideBox.status==='update'" :label="1">是</el-radio>
            <div class="common-explain color-warning">说明：选择选项'是'，此记录不可删除，可编辑，选择选项'否'，此记录可删除，可编辑</div>
          </el-form-item>

          <el-form-item label="排序:" prop="orders">
            <el-input-number v-model="systemRecord.orders" placeholder="请输入系统排排序" style="width:100%" show-word-limit maxlength="4" />
          </el-form-item>
          <el-form-item label="系统类型:" prop="systemType">
            <el-select v-model="systemRecord.systemType" :disabled="sideBox.status==='up1date'" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in systemTypeOptions"
                :key="item.value"
                :label="item.text"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="系统描述:" prop="description">
            <el-input
              v-model="systemRecord.description"
              :rows="2"
              placeholder="请输入"
              maxlength="30"
              show-word-limit
              type="textarea" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存</el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  data() {
    var checkSystemTitle = (rule, value, callback) => {
      if (this.sideBox.status === 'create') {
        this.$store.dispatch('systemValidateExistByField', { value: value, field: 'title' }).then(response => {
          if (!response) {
            callback()
          } else {
            return callback(new Error('系统名称已存在,请重新输入系统名称'))
          }
        }).catch(() => {})
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        title: undefined,
        sort: '-orders'
      },
      multipleSelectionRecords: [],
      systemTypeOptions: [{
        value: 0,
        text: '内部系统'
      }, {
        value: 1,
        text: '外部接入'
      }, {
        value: 2,
        text: '三方接入'
      }, {
        value: 90,
        text: '框架自带'
      }],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },

      systemRecord: {
        title: '',
        basePath: '',
        description: '',
        icon: '',
        code: ''
      },
      systemRules: {
        title: [
          { required: true, message: '请输入系统标题', trigger: 'blur' },
          { required: true, validator: checkSystemTitle, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入系统编码', trigger: 'blur' },
          { required: true, validator: this.commonValidate.validateEngOrNum, trigger: 'blur' }
        ],
        basePath: [
          { required: true, message: '请输入系统路径', trigger: 'blur' }
        ],
        isDefault: [
          { required: true, message: '请选择应用类型', trigger: 'blur' }
        ],
        systemType: [
          { required: true, message: '请选择系统类型', trigger: 'blur' }
        ],
        orders: [
          { required: true, message: '请输入系统排序', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.pageSystem()
  },
  methods: {
    // 表格自带方法开始
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格行过滤
     */
    handleFilterHandler(filters) {
      if (filters.systemType) {
        this.listQuery.systemType = filters.systemType.join(',')
      }
      this.handleFilter()
    },
    /**
     * 表格行数据单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /**
     * 表格列排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '-orders'
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    async pageSystem() {
      const response = await this.$store.dispatch('pageSystem', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.pageSystem()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        title: undefined,
        sort: '-orders'
      }

      this.pageSystem()
    },

    /* 新增*/
    handleCreate() {
      this.systemRecord = {
        isDefault: 1,
        orders: 99
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增系统'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('saveSystem', this.systemRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 编辑*/
    handleUpdate(row) {
      this.systemRecord = Object.assign({}, row)
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: '编辑系统[' + row.title + ']'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.systemRecord)
          this.$store.dispatch('updateSystem', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          if (v.isDefault === 0) {
            ids.push(v.id)
          }
        })
        if (ids.length === 0) {
          this.msgWarning('你选择的数据都是内置数据,无权删除')
          return
        }
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('removeSystem', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功!')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
